// 预约表单页面
const apiService = require('../../../utils/api.js');
const app = getApp();

Page({
  data: {
    // 系统信息
    statusBarHeight: 0,
    
    // 预约参数
    storeId: '',
    serviceId: '',
    beauticianId: '',
    
    // 门店信息
    storeInfo: null,
    
    // 服务信息
    serviceInfo: null,
    
    // 美容师信息
    beauticianInfo: null,
    
    // 用户宠物列表
    petList: [],
    selectedPet: null,
    
    // 预约时间
    selectedDate: '',
    selectedTime: '',
    availableDates: [],
    availableTimes: [],
    
    // 服务时长
    selectedDuration: 60,
    durationOptions: [
      { value: 60, label: '1小时', price: 0 },
      { value: 90, label: '1.5小时', price: 20 },
      { value: 120, label: '2小时', price: 40 }
    ],
    
    // 地址信息
    selectedAddress: null,
    addressList: [],
    
    // 备注信息
    remark: '',
    
    // 价格信息
    basePrice: 0,
    durationPrice: 0,
    totalPrice: 0,
    
    // 页面状态
    isLoading: true,
    isSubmitting: false,
    
    // 表单验证
    formValid: false
  },

  onLoad(options) {
    // 获取系统信息
    this.getSystemInfo();
    
    // 获取预约参数
    const { storeId, serviceId, beauticianId } = options;
    this.setData({
      storeId: storeId || '',
      serviceId: serviceId || '',
      beauticianId: beauticianId || ''
    });
    
    // 初始化页面数据
    this.initPageData();
  },

  onShow() {
    // 检查是否有从服务列表页返回的服务
    if (app.globalData.selectedService) {
      const service = app.globalData.selectedService;
      this.setData({
        serviceId: service.id,
        serviceInfo: service,
        basePrice: service.price,
        selectedDuration: service.duration
      });
      // 清理全局数据，避免重复加载
      app.globalData.selectedService = null;
      this.calculatePrice();
    }

    // 刷新用户宠物列表
    this.loadUserPets();
    // 刷新地址列表
    this.loadAddressList();
  },

  // 获取系统信息
  getSystemInfo() {
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight
    });
  },

  // 初始化页面数据
  async initPageData() {
    try {
      this.setData({ isLoading: true });
      
      // 并行加载数据
      await Promise.all([
        this.loadStoreInfo(),
        this.loadServiceInfo(),
        this.loadBeauticianInfo(),
        this.loadUserPets(),
        this.loadAddressList(),
        this.loadAvailableDates()
      ]);
      
      // 计算价格
      this.calculatePrice();
      
      this.setData({ isLoading: false });
    } catch (error) {
      console.error('初始化页面数据失败:', error);
      this.setData({ isLoading: false });
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
    }
  },

  // 加载门店信息
  async loadStoreInfo() {
    if (!this.data.storeId) return;
    
    try {
      const storeManager = app.getStoreManager();
      const storeInfo = await storeManager.getStoreById(this.data.storeId);
      if (storeInfo) {
        this.setData({
          storeInfo: storeInfo
        });
      } else {
        console.error('获取门店详情失败: 门店不存在');
        // 显示错误提示
        wx.showToast({
          title: '门店信息加载失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('加载门店信息失败:', error);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none'
      });
    }
  },

  // 加载服务信息
  async loadServiceInfo() {
    if (!this.data.serviceId) return;
    
    // 使用模拟数据
    const mockServices = {
      '1': {
        id: '1',
        name: '基础洗澡',
        price: 80,
        duration: 60,
        description: '基础清洁洗澡服务，包含吹干造型'
      },
      '2': {
        id: '2',
        name: '精致美容',
        price: 150,
        duration: 120,
        description: '全套美容护理，包含洗澡、修剪、造型'
      }
    };
    
    const serviceInfo = mockServices[this.data.serviceId] || mockServices['1'];
    this.setData({
      serviceInfo,
      basePrice: serviceInfo.price,
      selectedDuration: serviceInfo.duration
    });
  },

  // 加载美容师信息
  async loadBeauticianInfo() {
    if (!this.data.beauticianId) return;
    
    try {
      const result = await apiService.getEmployeeDetail(this.data.beauticianId);
      if (result.success) {
        this.setData({ beauticianInfo: result.data });
      } else {
        console.error('获取美容师信息失败:', result.message);
      }
    } catch (error) {
      console.error('加载美容师信息失败:', error);
    }
  },

  // 加载用户宠物列表
  async loadUserPets() {
    try {
      // 使用DataManager获取宠物列表，保持缓存一致性
      const dataManager = app.getDataManager();
      const petData = await dataManager.getPetList();
      
      if (petData && petData.length > 0) {
        this.setData({
          petList: petData,
          selectedPet: petData[0] // 默认选择第一个宠物
        });
      } else {
        console.log('用户暂无宠物信息');
        this.setData({
          petList: [],
          selectedPet: null
        });
      }
    } catch (error) {
      console.error('加载宠物列表失败:', error);
      this.setData({
        petList: [],
        selectedPet: null
      });
    }
  },

  // 加载地址列表
  async loadAddressList() {
    try {
      const result = await apiService.getUserAddresses();
      if (result.success && result.data.length > 0) {
        this.setData({
          addressList: result.data,
          selectedAddress: result.data.find(addr => addr.isDefault) || result.data[0]
        });
      } else {
        console.log('用户暂无地址信息');
        this.setData({
          addressList: [],
          selectedAddress: null
        });
      }
    } catch (error) {
      console.error('加载地址列表失败:', error);
    }
  },

  // 加载可预约日期
  async loadAvailableDates() {
    const dates = [];
    const today = new Date();
    
    // 生成未来7天的日期
    for (let i = 0; i < 7; i++) {
      const date = new Date(today);
      date.setDate(today.getDate() + i);
      
      const dateStr = date.toISOString().split('T')[0];
      const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      const dayName = dayNames[date.getDay()];
      
      dates.push({
        date: dateStr,
        display: i === 0 ? '今天' : i === 1 ? '明天' : `${date.getMonth() + 1}/${date.getDate()}`,
        dayName,
        available: true
      });
    }
    
    this.setData({
      availableDates: dates,
      selectedDate: dates[0].date
    });
    
    // 加载第一天的可用时间
    this.loadAvailableTimes(dates[0].date);
  },

  // 加载可预约时间
  async loadAvailableTimes(date) {
    // 生成时间段
    const times = [];
    const startHour = 9;
    const endHour = 18;
    
    for (let hour = startHour; hour < endHour; hour++) {
      for (let minute = 0; minute < 60; minute += 30) {
        const timeStr = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`;
        times.push({
          time: timeStr,
          available: Math.random() > 0.3 // 随机生成可用性
        });
      }
    }
    
    this.setData({
      availableTimes: times,
      selectedTime: times.find(t => t.available)?.time || ''
    });
  },

  // 切换服务
  onChangeService() {
    wx.navigateTo({
      url: `/pages/store/store-detail/index?storeId=${this.data.storeId}&from=booking-form`
    });
  },

  // 选择宠物
  onSelectPet() {
    if (this.data.petList.length === 0) {
      wx.showToast({
        title: '请先添加宠物',
        icon: 'none'
      });
      return;
    }
    
    const petNames = this.data.petList.map(pet => pet.name);
    wx.showActionSheet({
      itemList: petNames,
      success: (res) => {
        const selectedPet = this.data.petList[res.tapIndex];
        this.setData({ selectedPet });
        this.validateForm();
      }
    });
  },

  // 选择日期
  onSelectDate(e) {
    const date = e.currentTarget.dataset.date;
    this.setData({ selectedDate: date });
    this.loadAvailableTimes(date);
    this.validateForm();
  },

  // 选择时间
  onSelectTime(e) {
    const time = e.currentTarget.dataset.time;
    this.setData({ selectedTime: time });
    this.validateForm();
  },

  // 选择服务时长
  onSelectDuration(e) {
    const duration = parseInt(e.currentTarget.dataset.duration);
    this.setData({ selectedDuration: duration });
    this.calculatePrice();
    this.validateForm();
  },

  // 选择地址
  onSelectAddress() {
    wx.navigateTo({
      url: '/pages/user/address-list/index?mode=select'
    });
  },

  // 备注输入
  onRemarkInput(e) {
    this.setData({
      remark: e.detail.value
    });
  },

  // 计算价格
  calculatePrice() {
    const { basePrice, selectedDuration, durationOptions } = this.data;
    const durationOption = durationOptions.find(opt => opt.value === selectedDuration);
    const durationPrice = durationOption ? durationOption.price : 0;
    const totalPrice = basePrice + durationPrice;
    
    this.setData({
      durationPrice,
      totalPrice
    });
  },

  // 表单验证
  validateForm() {
    const { selectedPet, selectedDate, selectedTime, selectedAddress } = this.data;
    const formValid = selectedPet && selectedDate && selectedTime && selectedAddress;
    this.setData({ formValid });
  },

  // 提交预约
  async onSubmitBooking() {
    if (!this.data.formValid) {
      wx.showToast({
        title: '请完善预约信息',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.isSubmitting) return;
    
    try {
      this.setData({ isSubmitting: true });
      
      const bookingData = {
        storeId: this.data.storeId,
        serviceId: this.data.serviceId,
        beauticianId: this.data.beauticianId,
        petId: this.data.selectedPet._id,
        appointmentDate: this.data.selectedDate,
        appointmentTime: this.data.selectedTime,
        duration: this.data.selectedDuration,
        addressId: this.data.selectedAddress.id,
        remark: this.data.remark,
        totalPrice: this.data.totalPrice
      };
      
      const result = await apiService.createBooking(bookingData);
      
      if (result.success) {
        wx.showToast({
          title: '预约成功',
          icon: 'success'
        });
        
        setTimeout(() => {
          wx.navigateTo({
            url: `/pages/pay/order-detail/index?appointmentId=${result.data._id}`
          });
        }, 1500);
      } else {
        throw new Error(result.message || '预约失败');
      }
    } catch (error) {
      console.error('提交预约失败:', error);
      wx.showToast({
        title: error.message || '预约失败',
        icon: 'error'
      });
    } finally {
      this.setData({ isSubmitting: false });
    }
  },

  // 返回上一页
  onBack() {
    wx.navigateBack();
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.initPageData().finally(() => {
      wx.stopPullDownRefresh();
    });
  }
});
